package com.fhzz.controller;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipInputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricProcessInstanceQuery;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.runtime.ProcessInstanceQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.fhzz.model.Process;
import com.fhzz.model.Result;
import com.fhzz.model.Role;
import com.fhzz.model.Role_permission;
import com.fhzz.model.RunningProcess;
import com.fhzz.model.User;
import com.fhzz.model.User_role;
import com.fhzz.service.LeaveService;
import com.fhzz.service.SystemService;
import com.fhzz.service.WorkflowService;


import com.fhzz.model.HistoryProcess;
import com.fhzz.model.LeaveApply;
import com.fhzz.model.LeaveTask;
import com.fhzz.model.PageInfo;
import com.fhzz.model.Permission;

@Controller
public class ActivityController {
	
	@Autowired
	private RepositoryService rep;
	
	@Autowired
	private WorkflowService workflowService;
	
	@Autowired
	private LeaveService leaveService;
	
	@Autowired
	private RuntimeService runservice;
	
	@Autowired
	private SystemService systemService;
	
	public ProcessEngine processEngine =  ProcessEngines.getDefaultProcessEngine();
	
	@GetMapping("processList")
	public String processList() {
		return "processList";
	}
	
	/**
	 * 1、部署流程
	 * @return
	 */
	@RequestMapping("demo")
	public String demo() {
		Deployment deployment = ProcessEngines.getDefaultProcessEngine().getRepositoryService()
				.createDeployment()
				.name("leave")
				.addClasspathResource("processes/leave.bpmn")
				.deploy();
		System.out.println("部署id:"+deployment.getId());
		System.out.println("部署流程名称:"+deployment.getName());
		return deployment.getName();
	}
	
	/**
	 * 上传方式部署流程
	 * @param file
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/uploadWorkflow", method = RequestMethod.POST)
	public String fileupload(@RequestParam("file") MultipartFile file, 
			HttpServletRequest request) {
		try {
			String filename = file.getOriginalFilename();
			InputStream is = file.getInputStream();
			ZipInputStream zipInputStream = new ZipInputStream(is);
			String name = filename.substring(0,filename.lastIndexOf("."));
			Deployment deployment = workflowService.createDeployment(name, zipInputStream);
			System.out.println(deployment.getName());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "processList";
	}
	
	
	/**
	 * 获取部署流程列表
	 * @param current
	 * @param rowCount
	 * @return
	 */
	@GetMapping(value = "/getProcessList")
	@ResponseBody
	public PageInfo getlist(@RequestParam("page") int current, 
			@RequestParam("limit") int rowCount) {
		int firstrow = (current - 1) * rowCount;
		List<ProcessDefinition> list = rep.createProcessDefinitionQuery().listPage(firstrow, rowCount);
		int total = rep.createProcessDefinitionQuery().list().size();
		List<Process> resultList = new ArrayList<Process>();
		list.forEach(pro -> {
			Process p = new Process();
			p.setId(pro.getId());
			p.setDeploymentId(pro.getDeploymentId());
			p.setKey(pro.getKey());
			p.setName(pro.getName());
			p.setResourceName(pro.getResourceName());
			p.setDiagramresourcename(pro.getDiagramResourceName());
			resultList.add(p);
		});
		
		PageInfo page = new PageInfo();
		page.setCode("0");
		page.setCount(total);
		page.setData(resultList);
		return page;
	}
	
	
	@RequestMapping(value = "/deleteDeploy", method = RequestMethod.POST)
	@ResponseBody
	public void deletedeploy(@RequestParam("deployId") String deployid) throws Exception {
		workflowService.deleteDeploy(deployid);
	}
	
	
	@RequestMapping(value = "/leaveApply")
	public String leave() {
		return "leaveApply";
	}
	
	
	/**
	 * 启动请假流程
	 * @param session
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/startLeave",method = RequestMethod.POST)
	@ResponseBody
	public Result startLeave(HttpSession session,HttpServletRequest request) {
		String leave_type = request.getParameter("leave_type");
		String start_time = request.getParameter("start_time");
		String end_time = request.getParameter("end_time");
		String reason = request.getParameter("reason");
		LeaveApply apply = new LeaveApply();
		apply.setLeave_type(leave_type);
		apply.setStart_time(start_time);
		apply.setEnd_time(end_time);
		apply.setReason(reason);
		String userid = (String) session.getAttribute("username");
		Map<String, Object> variables = new HashMap<String, Object>();
		variables.put("applyuserid", userid);
		ProcessInstance ins = leaveService.startWorkflow(apply, userid, variables);
		System.out.println("流程id" + ins.getId() + "已启动");
		return Result.success();
	}
	
	/**
	 * 我发起的请假流程
	 * @return
	 */
	@RequestMapping(value = "myleaves", method = RequestMethod.GET)
	String myleaves() {
		return "myleaves";
	}
	
	/**
	 * 查询我发起的流程
	 * @param session
	 * @param current
	 * @param rowCount
	 * @return
	 */
	@RequestMapping(value = "/getMyProcessList")
	@ResponseBody
	public PageInfo setupprocess(HttpSession session, @RequestParam("page") int current,
			@RequestParam("limit") int rowCount) {
		
		int firstrow = (current - 1) * rowCount;
		String userid = (String) session.getAttribute("username");
		int total = workflowService.getHistoricProcessInstanceCount(userid, "leave");
		
//		List<ProcessInstance> list = workflowService.getUserProcessInstance("leave", userid, firstrow, rowCount);
		
		List<HistoricProcessInstance> list = workflowService
				.getHistoricProcessInstanceList(userid, "leave", firstrow, rowCount);
		List<RunningProcess> resultList = new ArrayList<RunningProcess>();
		list.forEach(p -> {
			RunningProcess process = new RunningProcess();
			
			process.setActivityid(p.getEndActivityId());
			process.setBusinesskey(p.getBusinessKey());
			process.setExecutionid(p.getId());
			process.setProcessInstanceid(p.getId());
			
			//获取本地业务申请
			LeaveApply l = leaveService.getleave(Integer.parseInt(p.getBusinessKey()));
			if (l.getUser_id().equals(userid)) {
				resultList.add(process);
			}
			
		});
		
		PageInfo page = new PageInfo();
		page.setCode("0");
		page.setCount(total);
		page.setData(resultList);
		return page;
		
	}
	
	/**
	 * 查看流程详情
	 * @param executionid
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "traceprocess/{processInstanceId}", method = RequestMethod.GET)
	public void traceprocess(@PathVariable("processInstanceId")String processInstanceId, 
			HttpServletResponse response)throws Exception {
		try {
            InputStream is = workflowService.getDiagram(processInstanceId);
            if (is == null)
                return;

            OutputStream out = response.getOutputStream();
    		 // 输出图片内容
            byte[] b = new byte[1024];
            int len;
            while ((len = is.read(b, 0, 1024)) != -1) {
                out.write(b, 0, len);
            }
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
	}
	
	/**
	 * 我正在参与的请假流程页面
	 * @return
	 */
	@RequestMapping(value = "myleaveprocess", method = RequestMethod.GET)
	public String myleaveprocess() {
		return "myleaveprocess";
	}
	
	
	/**
	 * 我正在参与的请假流程
	 * @param session
	 * @param current
	 * @param rowCount
	 * @return
	 */
	@RequestMapping(value = "involvedprocess") // 参与的正在运行的请假流程
	@ResponseBody
	public PageInfo allexeution(HttpSession session, @RequestParam("page") int current,
			@RequestParam("limit") int rowCount) {
		int firstrow = (current - 1) * rowCount;
		String userid = (String) session.getAttribute("username");
		int total = workflowService.getUserProcessInstanceCount("leave", userid);
		List<ProcessInstance> list = workflowService.getUserProcessInstance("leave", userid, firstrow, rowCount);
		List<RunningProcess> resultList = new ArrayList<RunningProcess>();
		list.forEach(p -> {
			RunningProcess process = new RunningProcess();
			process.setActivityid(p.getActivityId());
			process.setBusinesskey(p.getBusinessKey());
			process.setExecutionid(p.getId());
			process.setProcessInstanceid(p.getProcessInstanceId());
			resultList.add(process);
		});
		PageInfo page = new PageInfo();
		page.setCode("0");
		page.setCount(total);
		page.setData(resultList);
		return page;
	}
	
	/**
	 * 部门领导审批页面
	 * @return
	 */
	@RequestMapping(value = "/deptleaderaudit", method = RequestMethod.GET)
	public String mytask() {
		return "deptleaderaudit";
	}
	
	
	/**
	 * 获取部门领导任务列表
	 * @param session
	 * @param current
	 * @param rowCount
	 * @return
	 */
	@RequestMapping(value = "/getDeptTaskList", method = RequestMethod.GET)
	@ResponseBody
	public PageInfo getDeptTaskList(HttpSession session, @RequestParam("page") int current,
		@RequestParam("limit") int rowCount) {
		PageInfo page = new PageInfo();
		page.setCode("0");
		page.setCount(0);
		page.setData(new ArrayList<LeaveTask>());
		// 先做权限检查，对于没有部门领导审批权限的用户,直接返回空
		String userid = (String) session.getAttribute("username");
		int uid = systemService.getUidByUsername(userid);
		User user = systemService.getUserById(uid);
		
		List<User_role> userroles = user.getUser_roles();
		if (userroles == null) {
			return page;
		}
		boolean flag = false;// 默认没有权限
		
		for (int k = 0; k < userroles.size(); k++) {
			User_role ur = userroles.get(k);
			Role r = ur.getRole();
			int roleid = r.getRid();
			Role role = systemService.getRoleById(roleid);
			List<Role_permission> p = role.getRole_permission();
			for (int j = 0; j < p.size(); j++) {
				Role_permission rp = p.get(j);
				Permission permission = rp.getPermission();
				if (permission.getPermissionname().equals("部门领导审批")) {
					flag = true;
				}
			}
		}
		if (flag == false){// 无权限
			return page;
		} else {
			int firstrow = (current - 1) * rowCount;
			List<LeaveApply> results = leaveService.getPageDeptTask(userid, firstrow, rowCount);
			int totalsize = leaveService.getAllDeptTask(userid);
			
			List<LeaveTask> tasks = new ArrayList<LeaveTask>();
			results.forEach(apply -> {
				LeaveTask task = new LeaveTask();
				task.setApply_time(apply.getApply_time());
				task.setUser_id(apply.getUser_id());
				task.setEnd_time(apply.getEnd_time());
				task.setId(apply.getId());
				task.setLeave_type(apply.getLeave_type());
				task.setProcess_instance_id(apply.getProcess_instance_id());
				task.setProcessdefid(apply.getTask().getProcessDefinitionId());
				task.setReason(apply.getReason());
				task.setStart_time(apply.getStart_time());
				task.setTaskcreatetime(apply.getTask().getCreateTime());
				task.setTaskid(apply.getTask().getId());
				task.setTaskname(apply.getTask().getName());
				tasks.add(task);
			});
			
			page.setCount(totalsize);
			page.setData(tasks);
			return page;
		}
	}
	
	/**
	 * 部门领导处理页面
	 * @return
	 */
	@RequestMapping(value = "/deptLeaderDeal", method = RequestMethod.GET)
	public ModelAndView deptLeaderDeal(String data) {
		ModelAndView view = new ModelAndView();
		view.setViewName("deptLeaderDeal");
		return view;
	}
	
	/**
	 * 部门领导审批
	 * @param session
	 * @param taskid
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/deptComplete", method = RequestMethod.POST)
	@ResponseBody
	public Result deptcomplete(HttpSession session,
			HttpServletRequest req) {
		String userid = (String) session.getAttribute("username");
		Map<String, Object> variables = new HashMap<String, Object>();
		String approve = req.getParameter("deptleaderapprove");
		String taskid = req.getParameter("taskid");
		variables.put("deptleaderapprove", approve);
		workflowService.completeTask(userid, taskid, variables);
		return Result.success();
	}
	
	/**
	 * 人事审批列表
	 * @return
	 */
	@RequestMapping(value = "/hraudit", method = RequestMethod.GET)
	public String hr() {
		return "hraudit";
	}
	
	/**
	 * 获取人事审批任务列表
	 * @param session
	 * @param current
	 * @param rowCount
	 * @return
	 */
	@RequestMapping(value = "/getHrTaskList", method = RequestMethod.GET)
	@ResponseBody
	public PageInfo getHrTaskList(HttpSession session, @RequestParam("page") int current,
			@RequestParam("limit") int rowCount) {
		PageInfo page = new PageInfo();
		page.setCode("0");
		page.setCount(0);;
		page.setData(new ArrayList<LeaveTask>());
		// 先做权限检查，对于没有人事权限的用户,直接返回空
		String userid = (String) session.getAttribute("username");
		int uid = systemService.getUidByUsername(userid);
		User user = systemService.getUserById(uid);
		List<User_role> userroles = user.getUser_roles();
		if (userroles == null) {
			return page;
		}
		boolean flag = false;// 默认没有权限
		for (int k = 0; k < userroles.size(); k++) {
			User_role ur = userroles.get(k);
			Role r = ur.getRole();
			int roleid = r.getRid();
			Role role = systemService.getRoleById(roleid);
			List<Role_permission> p = role.getRole_permission();
			for (int j = 0; j < p.size(); j++) {
				Role_permission rp = p.get(j);
				Permission permission = rp.getPermission();
				if (permission.getPermissionname().equals("人事审批")) {
					flag = true;
				}
			}
		}
		if (flag == false){// 无权限
			return page;
		} else {
			int firstrow = (current - 1) * rowCount;
			List<LeaveApply> results = leaveService.getPageHrTask(userid, firstrow, rowCount);
			int totalsize = leaveService.getAllHrTask(userid);
			List<LeaveTask> tasks = new ArrayList<LeaveTask>();
			results.forEach(apply -> {
				LeaveTask task = new LeaveTask();
				task.setApply_time(apply.getApply_time());
				task.setUser_id(apply.getUser_id());
				task.setEnd_time(apply.getEnd_time());
				task.setId(apply.getId());
				task.setLeave_type(apply.getLeave_type());
				task.setProcess_instance_id(apply.getProcess_instance_id());
				task.setProcessdefid(apply.getTask().getProcessDefinitionId());
				task.setReason(apply.getReason());
				task.setStart_time(apply.getStart_time());
				task.setTaskcreatetime(apply.getTask().getCreateTime());
				task.setTaskid(apply.getTask().getId());
				task.setTaskname(apply.getTask().getName());
				tasks.add(task);
			});
			page.setCount(totalsize);
			page.setData(tasks);
			return page;
		}
	}
	
	
	/**
	 * 部门领导处理页面
	 * @return
	 */
	@RequestMapping(value = "/hrDeal", method = RequestMethod.GET)
	public ModelAndView hrDeal(String data) {
		ModelAndView view = new ModelAndView();
		view.setViewName("hrDeal");
		return view;
	}
	
	/**
	 * 人事审批
	 * @param session
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/hrComplete", method = RequestMethod.POST)
	@ResponseBody
	public Result hrcomplete(HttpSession session, HttpServletRequest req) {
		String userid = (String) session.getAttribute("username");
		Map<String, Object> variables = new HashMap<String, Object>();
		String approve = req.getParameter("hrapprove");
		String taskid = req.getParameter("taskid");
		variables.put("hrapprove", approve);
		workflowService.completeTask(userid, taskid, variables);
		return Result.success();
	}
	
	/**
	 * 销假页面
	 * @return
	 */
	@RequestMapping(value = "/reportBack", method = RequestMethod.GET)
	public String reprotback() {
		return "reportback";
	}
	
	
	/**
	 * 销假任务列表
	 * @param session
	 * @param current
	 * @param rowCount
	 * @return
	 */
	@RequestMapping(value = "/getXjTaskList", method = RequestMethod.GET)
	@ResponseBody
	public PageInfo getXJtasklist(HttpSession session, @RequestParam("page") int current,
			@RequestParam("limit") int rowCount) {
		int firstrow = (current - 1) * rowCount;
		String userid = (String) session.getAttribute("username");
		List<LeaveApply> results = leaveService.getPageXjTask(userid, firstrow, rowCount);
		int totalsize = leaveService.getAllXjTask(userid);
		List<LeaveTask> tasks = new ArrayList<LeaveTask>();
		for (LeaveApply apply : results) {
			LeaveTask task = new LeaveTask();
			task.setApply_time(apply.getApply_time());
			task.setUser_id(apply.getUser_id());
			task.setEnd_time(apply.getEnd_time());
			task.setId(apply.getId());
			task.setLeave_type(apply.getLeave_type());
			task.setProcess_instance_id(apply.getProcess_instance_id());
			task.setProcessdefid(apply.getTask().getProcessDefinitionId());
			task.setReason(apply.getReason());
			task.setStart_time(apply.getStart_time());
			task.setTaskcreatetime(apply.getTask().getCreateTime());
			task.setTaskid(apply.getTask().getId());
			task.setTaskname(apply.getTask().getName());
			tasks.add(task);
		}
		PageInfo page = new PageInfo();
		page.setCode("0");
		page.setCount(totalsize);
		page.setData(tasks);
		return page;
	}
	
	
	/**
	 * 销假处理
	 * @return
	 */
	@RequestMapping(value = "/xjDeal", method = RequestMethod.GET)
	public String xjDeal() {
		return "xjDeal";
	}
	
	
	/**
	 * 完成销假
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/xjComplete", method = RequestMethod.POST)
	@ResponseBody
	public Result reportbackcomplete(HttpServletRequest req) {
		String realStartTime = req.getParameter("realStartTime");
		String realEndTime = req.getParameter("realEndTime");
		String taskid = req.getParameter("taskid");
		leaveService.completeReportBack(taskid, realStartTime, realEndTime);
		return Result.success();
	}
	
	/**
	 * 调整申请
	 * @return
	 */
	@RequestMapping(value = "/modifyApply", method = RequestMethod.GET)
	public String modifyapply() {
		return "modifyapply";
	}
	
	
	/**
	 * 获取可调整的请假申请
	 * @param session
	 * @param current
	 * @param rowCount
	 * @return
	 */
	@RequestMapping(value = "/getModifyApplyList", method = RequestMethod.GET)
	@ResponseBody
	public PageInfo getModifyApplyList(HttpSession session, @RequestParam("page") int current,
		@RequestParam("limit") int rowCount) {
		int firstrow = (current - 1) * rowCount;
		String userid = (String) session.getAttribute("username");
		List<LeaveApply> results = leaveService.getPageUpdateApplyTask(userid, firstrow, rowCount);
		int totalsize = leaveService.getAllUpdateApplyTask(userid);
		List<LeaveTask> tasks = new ArrayList<LeaveTask>();
		results.forEach(apply -> {
			LeaveTask task = new LeaveTask();
			task.setApply_time(apply.getApply_time());
			task.setUser_id(apply.getUser_id());
			task.setEnd_time(apply.getEnd_time());
			task.setId(apply.getId());
			task.setLeave_type(apply.getLeave_type());
			task.setProcess_instance_id(apply.getProcess_instance_id());
			task.setProcessdefid(apply.getTask().getProcessDefinitionId());
			task.setReason(apply.getReason());
			task.setStart_time(apply.getStart_time());
			task.setTaskcreatetime(apply.getTask().getCreateTime());
			task.setTaskid(apply.getTask().getId());
			task.setTaskname(apply.getTask().getName());
			tasks.add(task);
		});
		PageInfo page = new PageInfo();
		page.setCode("0");
		page.setCount(totalsize);
		page.setData(tasks);
		return page;
	}
	
	/**
	 * 调整申请处理
	 * @return
	 */
	@RequestMapping(value = "/modifyApplyDeal", method = RequestMethod.GET)
	public String modifyApplyDeal() {
		return "modifyApplyDeal";
	}
	
	
	/**
	 * 调整请假申请
	 * @param taskid
	 * @param leave
	 * @param reapply
	 * @return
	 */
	@RequestMapping(value = "updateApply", method = RequestMethod.GET)
	@ResponseBody
	public Result updateApply(String taskid, LeaveApply leave,String reapply) {
		leaveService.updateComplete(taskid, leave, reapply);
		return Result.success();
	}
	
	/**
	 * 请假历史页面
	 * @return
	 */
	@RequestMapping(value = "/historyProcess", method = RequestMethod.GET)
	public String history() {
		return "historyprocess";
	}
	
	
	/**
	 * 我的请假历史列表
	 * @param session
	 * @param current
	 * @param rowCount
	 * @return
	 */
	@RequestMapping(value = "/getFinishProcessList", method = RequestMethod.GET)
	@ResponseBody
	public PageInfo getHistory(HttpSession session, @RequestParam("page") int current,
			@RequestParam("limit") int rowCount) {
		String userid = (String) session.getAttribute("username");
		HistoricProcessInstanceQuery process = workflowService.getHistoricProcess("leave", userid);
		int total = (int) process.count();
		int firstrow = (current - 1) * rowCount;
		List<HistoricProcessInstance> hisProes = process.listPage(firstrow, rowCount);
		
		List<HistoryProcess> list = new ArrayList<HistoryProcess>();
		
		hisProes.forEach(history -> {
			HistoryProcess his = new HistoryProcess();
			String bussinesskey = history.getBusinessKey();
			LeaveApply apply = leaveService.getleave(Integer.parseInt(bussinesskey));
			his.setLeaveapply(apply);
			his.setBusinessKey(bussinesskey);
			his.setProcessDefinitionId(history.getProcessDefinitionId());
			list.add(his);
		});
		
		PageInfo page = new PageInfo();
		page.setCode("0");
		page.setCount(total);
		page.setData(list);
		return page;
	}
	
	
	/**
	 * 流程详情页面
	 * @return
	 */
	@RequestMapping(value = "/processinfo", method = RequestMethod.GET)
	public String processinfo() {
		return "processinfo";
	}
	
	/**
	 * 查询结束流程详情
	 * @param instanceid
	 * @return
	 */
	@RequestMapping(value = "/getProcessInfo")
	@ResponseBody
	public PageInfo processinfo(HttpServletRequest req) {
		String instanceid = req.getParameter("instanceId");
		List<HistoricActivityInstance> his = workflowService.getHistoricActivityInstanceById(instanceid);
		PageInfo page = new PageInfo();
		page.setCode("0");
		page.setCount(his.size());
		page.setData(his);
		return page;
	}
	
}
